import { GenericEnvStore } from "@/modules/dev-env/store/generic-env-store.ts";
import type { LocalVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import type { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import type { EnvTableAction } from "@/modules/dev-env/store/types.ts";
import { execInTerminal, openInTerminal } from "@/util/system-utils2.ts";
import { KafkaMirror } from "@/modules/dev-env/middleware/kafka/kafka-mirror.ts";
import { hc } from "@/framework/vue/util/render.ts";
import { EditOutlined } from "@ant-design/icons-vue";
import { openExternal } from "@/util/shell.ts";

export class KafkaEnvStore extends GenericEnvStore<KafkaEnvStore> {
  constructor() {
    super("kafka");
    this.icon = "icon-kafka";
    this.pageConfig = {
      showCurrentAction: false,
      showSetting: false,
    };
    this.tableActions = this._tableActions();
  }

  private _tableActions(): EnvTableAction[] {
    return [
      {
        key: "kafka-server-start",
        name: "kafka-server-start",
        icon: "icon-terminal",
        onClick: (version: LocalVersionItem) => this._execCmd(version, `kafka-server-start config/server.properties`),
      },
      {
        key: "server.properties",
        name: "server.properties",
        icon: hc(EditOutlined),
        onClick: (version: LocalVersionItem) => openExternal(path.join(version.installPath, "config/server.properties")),
      },
      {
        key: "open-in-terminal",
        name: "在终端打开",
        icon: "icon-terminal",
        onClick: (version: LocalVersionItem) => openInTerminal(version.installPath, { subPath: ["bin/windows", "bin"] }),
      },
    ];
  }

  private _execCmd(version: LocalVersionItem, cmd: string) {
    execInTerminal(cmd, {
      cwd: version.installPath,
      subPath: ["bin/windows", "bin"],
    });
  }

  protected getMirrors0(): BaseEnvMirror[] {
    return [
      new KafkaMirror("aliyun"),
      new KafkaMirror("tencent"),
      new KafkaMirror("tsinghua"),
      new KafkaMirror("apache"),
      // ...
    ];
  }

  protected compareVersion(a: LocalVersionItem, b: LocalVersionItem): number {
    return 0;
  }

  protected async getVersionInfo(versionDir: string): Promise<LocalVersionItem | undefined> {
    // kafka_2.13-3.9.1
    const folderName = path.basename(versionDir);
    if (!folderName.startsWith("kafka")) return undefined;
    const runserver = path.join(versionDir, "bin/kafka-server-start.sh");
    if (!(await native.fs.exists(runserver))) return undefined;

    return Promise.resolve({
      version: folderName,
      installPath: versionDir,
    });
  }
}
